package router

import (
	_ "embed"
	"io"
	"net/http"
	"os"
	"strings"
	"unicode"
	"wms/service/response"
	"wms/util"

	"github.com/icetech233/gin"
	"github.com/xuri/excelize/v2"
)

//go:embed menu.json
var menuJsonData []byte

func menuJson(c *gin.Context) {
	c.Writer.WriteHeader(200)
	c.Writer.Header()["Content-Type"] = []string{"application/json; charset=utf-8"}
	_, _ = c.Writer.Write(menuJsonData)
}

func faviconIco(c *gin.Context) {
	c.Writer.WriteHeader(200)
	_, _ = c.Writer.Write([]byte(`nmsl`))
}

func ping(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "pong",
	})
}

func envList(c *gin.Context) {
	environ := os.Environ()
	path := os.Getenv("PATH")
	param := os.Getenv("PARAM")
	// "WMS_SVC_SERVICE_HOST=10.43.153.142",
	// "WMS_SVC_SERVICE_PORT=8081",
	// "WMS_SVC_PORT=tcp://10.43.153.142:8081",
	// "WMS_SVC_SERVICE_PORT=8081",
	// "PARAM=--spring.cloud.consul.host=consul.dev-middeware --spring.cloud.consul.port=8500 --server.port=80 --env=DEV --apollo.meta=http://192.168.1.81:8080"
	mapKv := make(map[string]string)
	if len(param) > 0 {
		fields := strings.FieldsFunc(param, unicode.IsSpace)
		//
		for _, field := range fields {
			curKV := strings.Split(field, "=")
			if len(field) == 2 {
				cKey := strings.TrimPrefix(curKV[0], "--")
				mapKv[cKey] = curKV[1]
			}
		}
	}

	// 分割等于号 分割 空格
	m := map[string]any{
		"path":      path,
		"param_raw": param,
		"env":       environ,
	}
	response.OkWithData(m, c)
}

func recordLog(c *gin.Context) {
	util.Log("record log:")
	body, err := io.ReadAll(c.Request.Body)
	if err != nil {
		return
	}
	util.Log(string(body))
	response.Ok(c)
}

func uploadExcel(c *gin.Context) {
	fileHeader, err := c.FormFile("files")
	if err != nil {
		response.Fail(-1, err.Error(), fileHeader, c)
		return
	}
	m := make(map[string]any)
	m["size"] = fileHeader.Size
	m["filename"] = fileHeader.Filename
	fh1, err := fileHeader.Open()
	if err != nil {
		response.Fail(-1, err.Error(), fh1, c)
		return
	}
	defer fh1.Close()
	f, err := excelize.OpenReader(fh1)
	if err != nil {
		response.Fail(-1, err.Error(), f.SheetCount, c)
		return
	}
	defer f.Close()
	sheetName0 := f.GetSheetName(0)
	arr, err := f.GetRows(sheetName0)
	if err != nil {
		response.Fail(-1, err.Error(), arr, c)
		return
	}

	m["data"] = arr
	response.OkWithData(m, c)
}
